package com.lerning.edu.manage.controller;

import com.lerning.edu.beans.SysRole;
import com.lerning.edu.beans.page.PageList;
import com.lerning.edu.commons.util.StringUtil;
import com.lerning.edu.manage.context.GlobalContext;
import com.lerning.edu.manage.util.UserUtils;
import com.lerning.edu.services.SysReportService;
import com.lerning.edu.services.SysRoleService;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by FCHEN on 2016/12/13.
 */
@Controller
@RequestMapping("sysrole")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysReportService sysReportService;

    @ModelAttribute("sysRole")
    public SysRole get(@RequestParam(required=false) String id) {
        if (StringUtil.isNotBlank(id)){
            long _id = NumberUtils.toLong(id);
            return sysRoleService.queryById(_id);
        }else{
            return new SysRole();
        }
    }
    /**
     * 查询列表
     * @param sysRole
     * @return
     */
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = {"","/","list"})
    public String list(SysRole sysRole, HttpServletRequest request){
        request.setAttribute("sysRole",sysRole);
        return "sys/sysrole/list";
    }

    /**
     * 异步获取list资源
     * @param pageList
     * @return
     */
    @RequiresPermissions("sys:role:view")
    @RequestMapping("asynList")
    @ResponseBody
    public PageList asynList(PageList pageList){
        List<SysRole> roleList = UserUtils.getRoleList();
        pageList.setAaData(roleList);
        pageList.setiTotalRecords(roleList.size());
        pageList.setiTotalDisplayRecords(roleList.size());
        return pageList;
    }

    /**
     * 新增修改
     * @param id
     * @return
     */
    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = {"add","edit"},method = RequestMethod.GET)
    public String edit(Long id,  Model model){
        SysRole sysRole;
        if(id == null|| id < 1l ){ //add
            sysRole = new SysRole();
            int seq = sysRoleService.getMaxSeq();
            sysRole.setSeq(seq+2);
        }else{//edit
            sysRole = sysRoleService.queryById(id);
        }
        model.addAttribute("resourceList", UserUtils.getMenuList());
        model.addAttribute("sysRole",sysRole);
        return "sys/sysrole/edit";
    }

    /**
     * 新增修改角色报表
     * @param id
     * @return
     */
    @RequiresPermissions("sys:sysRoleReport:edit")
    @RequestMapping(value = "editReport",method = RequestMethod.GET)
    public String sysRoleReportEdit(Long id,  Model model){
        SysRole sysRole;
        if(id == null|| id < 1l ){
            sysRole = new SysRole();
        }else{
            sysRole = sysRoleService.queryById(id);
        }

        model.addAttribute("reportList", UserUtils.getReportList());
        model.addAttribute("sysRole",sysRole);
        return "sys/sysrole/editReport";
    }

    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "save",method = RequestMethod.POST )
    public String save(SysRole sysRole,HttpServletRequest request){
        sysRole.setOperator(UserUtils.getUser().getId());
//        sysRoleService.saveRole(sysRole);
        if( sysRole.getId() == null ){ //add
            sysRoleService.add(sysRole);
        }else{//edit
            sysRoleService.update(sysRole);
        }
        // 更新角色与菜单关联
        sysRoleService.deleteRoleResource(sysRole);
        if (sysRole.getResourceList().size() > 0){
            sysRoleService.insertRoleResource(sysRole);
        }
        // 清除用户角色缓存
        UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
        //TODO  成功失败结果页面
        return "redirect:list";
    }

    //
    @RequiresPermissions("sys:sysRoleReport:edit")
    @RequestMapping(value = "saveReport",method = RequestMethod.POST )
    public String sysRoleReportSave(SysRole sysRole,HttpServletRequest request){
        sysRole.setOperator(UserUtils.getUser().getId());
        // 更新角色与报表关联
        sysRoleService.deleteRoleReport(sysRole);
        if (sysRole.getReportList().size() > 0){
            sysRoleService.insertRoleReport(sysRole);
        }
        // 清除用户角色缓存
        UserUtils.removeCache(UserUtils.CACHE_REPORT_LIST);
        //TODO  成功失败结果页面
        return "redirect:list";
    }

    @RequiresPermissions("sys:role:delete")
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(SysRole sysRole){
        String result = "";
        if(!UserUtils.getUser().isAdmin() && sysRole.getSysData().equals(GlobalContext.YES)){
//            addMessage(redirectAttributes, "越权操作，只有超级管理员才能修改此数据！");
            result = "越权操作，只有超级管理员才能修改此数据！";
            return result;
//            return "redirect:" + adminPath + "/sys/role/?repage";
        }
        sysRole.setOperator(UserUtils.getUser().getId());
        sysRoleService.delete(sysRole);
        result = "禁用角色 " + sysRole.getName() + "成功";
        UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
        //TODO  成功失败结果页面
        return result;
    }

    /**
     * 验证角色名是否有效
     * @param oldName
     * @param name
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "checkName", method = RequestMethod.POST)
    public Boolean checkName(String oldName, String name) {
        if (name!=null && name.equals(oldName)) {
            return true;
        } else if (name!=null && sysRoleService.getRoleByName(name) == null) {
            return true;
        }
        return false;
    }
}
